package com.aistar.controller;


import com.aistar.pojo.Customer;
import com.aistar.service.CartService;
import com.aistar.service.CustomerService;
import com.aistar.util.Md5;
import com.aistar.util.ServerResponse;
import com.aistar.util.oss.AliOssUtil;
import com.aistar.util.sms.SmsUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.Date;
import java.util.UUID;

@Controller
public class CustomerController {
    @Autowired
    private CustomerService customerService;

    //用户登录（带有自动登录功能）
    //密码登录
    @PostMapping("/customer/login")
    @ResponseBody
    public ServerResponse login(Long Telno, String custPassword, String isAutoLogin, HttpServletRequest request ) throws ServletException, IOException {

        //给用户密码加密
        /*System.out.println("custPassword:"+custPassword);
        String pas = Md5.encoder(custPassword);
        System.out.println(pas);*/
        ServerResponse serverResponse = customerService.getByTelnoAndPwd(Telno,custPassword);

          /*  1. 若isAutoLogin没有自动登录功能，service 执行登功能
            2. 若isAutoLogin选择了自动登录，cookie，reponse.add（cookie），service 执行登功能*/

        if (serverResponse.getStatus()==1){//登录成功
            request.getSession().setAttribute("loginCustomer",(Customer)serverResponse.getData());
        }
        return  serverResponse;
    }


    @PostMapping("/customer/codeLogin")
    @ResponseBody
    public ServerResponse codeLogin(Long Telno, String isAutoLogin, HttpServletRequest request ) throws ServletException, IOException {

       ServerResponse serverResponse = customerService.getByTelnoReturnData(Telno);

          /*  1. 若isAutoLogin没有自动登录功能，service 执行登功能
            2. 若isAutoLogin选择了自动登录，cookie，reponse.add（cookie），service 执行登功能*/

        if (serverResponse.getStatus()==1){//登录成功
            request.getSession().setAttribute("loginCustomer",serverResponse.getData());
        }
        return  serverResponse;
    }


    @GetMapping("/customer/telno/{telno}")
    @ResponseBody
    public ServerResponse getbytelno(@PathVariable("telno") Long Telno) {
        ServerResponse serverResponse = customerService.getByTelno(Telno);
        System.out.println("Telno"+Telno);
        return serverResponse;
    }

    @PostMapping("/customer/code")
    @ResponseBody
    public ServerResponse getCode(Long telno) {
        if (telno == null) {
            ServerResponse serverResponse = ServerResponse.getDataFailed("请输入手机号"); //0 手机号为空
            return serverResponse;
        } else {
            ServerResponse serverResponse = customerService.getByTelno(telno);
            if (serverResponse.getStatus() == 1) {//手机号已经注册过，不能再注册，即不调用短信接口
                return serverResponse;
            } else {
                //用户尚未注册，调用短信接口
                // String code =  SmsUtil.getSms(Long.toString(telno));
                String code = "666666";
                System.out.println("code" + code);
                ServerResponse serverResponseCode = ServerResponse.getDataSuccess(code);
                serverResponseCode.setStatus(2);
                return serverResponseCode;
            }
        }
    }

    @PostMapping("/customer/codeL")
    @ResponseBody
    public ServerResponse getCodeLogin(Long telno) {
        if (telno == null) {
            ServerResponse serverResponse = ServerResponse.getDataFailed("请输入手机号"); //0 手机号为空
            return serverResponse;
        } else {
            ServerResponse serverResponse = customerService.getByTelno(telno);
            if (serverResponse.getStatus() == 1) {//手机号已经注册过，调用短信接口
                 //String code =  SmsUtil.getSms(Long.toString(telno));
                String code = "666666";
                System.out.println("code" + code);
                ServerResponse serverResponseCode = ServerResponse.getDataSuccess(code);
                serverResponseCode.setStatus(2);
                return serverResponseCode;
            } else {
                //用户尚未注册，调用短信接口
                return serverResponse;
            }
        }
    }

    @PostMapping("/customer/add")
    @ResponseBody
    public ServerResponse add(Long customerTelno,String customerPassword){
        Customer customer = new Customer();
        customer.setCustomerTelno(customerTelno);
        customer.setCustomerPassword(customerPassword);
        customer.setCustomerTime(new Date());//注册时间
        ServerResponse serverResponse =  customerService.save(customer);
        if (serverResponse.getStatus()==1){
            serverResponse = customerService.getByTelnoReturnData(customerTelno);
            return serverResponse;
        }
        return serverResponse;
    }

    //用户头像上传的功能  到阿里云服务器
    @RequestMapping(value = "/customer/upload/img", method = {RequestMethod.POST})
    @ResponseBody
    public ServerResponse upload(@RequestParam(value="file",required=false) MultipartFile imgFile, HttpServletRequest request) {

        //ModelAndView mav = new ModelAndView("customer/center");
        //获取到用户的id；
       // Customer customer = (Customer) request.getSession().getAttribute("loginCustomer");

        //用于测试
        Customer customer1 = (Customer)request.getSession().getAttribute("loginCustomer");
        Integer customerId = customer1.getCustomerId();
               
               Customer customer = (Customer) customerService.getById(customerId).getData();

                String originalFilename = imgFile.getOriginalFilename();
                String imgName = UUID.randomUUID().toString().replace("-","");
                String extName = originalFilename.substring(originalFilename.lastIndexOf("."));
                //String filepath = request.getSession().getServletContext().getRealPath("/upload");
                String fileName = imgName+extName;
                String url = null;
                try {
                    url = AliOssUtil.upload(fileName, imgFile.getBytes());
                } catch (IOException e) {
                    e.printStackTrace();
                }
                System.out.println(url);
                //将图片的路径给用户 再将用户存起来
                customer.setCustomerImages(url);
                 return customerService.modify(customer);


    }

    //查询用用户的信息
    @GetMapping("/customer/getMess/{customerId}")
    @ResponseBody
    public ServerResponse getCustomerMess(@PathVariable("customerId")Integer customerId){
        ServerResponse serverResponse = customerService.getById(customerId);
        return serverResponse;
    }

    @RequestMapping("/customer/outLogin")
    public String CustomerLogout(HttpServletRequest request){
        //1.从session中移除登录用户
        HttpSession session = request.getSession();
        session.removeAttribute("loginCustomer");
        //2.清除cookie的时间
       /* Cookie[] cookies = request.getCookies();
        if (cookies!=null &&cookies.length>0){
            for (Cookie cookie:cookies){
                if (cookie.getName().equals("autoLogin")){
                    cookie.setMaxAge(-1);
                }
            }
        }*/
        return "/customer/login";
    }



}

